//
//  MainViewController.swift
//  OnemeetingDemo
//
//  Created by zhangheng on 2019/11/18.
//  Copyright © 2019 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation

class MainViewController: HKViewController {
    let group = [
        KIconGroup.init(title: "召开", image: "ic_home_host"),
        KIconGroup.init(title: "加入", image: "ic_home_jion"),
        KIconGroup.init(title: "设置", image: "ic_home_shard"),
        KIconGroup.init(title: "邀请", image: "ic_home_invite")
    ]
    var buttomAndLabel:([ZHButton],[NSLabel]) = ([],[])
    
    let images = ["icon_home_more","icon_home_Introduction","icon_home_refresh"]
    var topButtoms:[ZHButton] = []
    
    var isprotocol:Bool = true
    
   
    lazy var windowk: MainWindow? = {
        let window = self.view.window as? MainWindow
        return window
    }()
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kWindowWidth, kWindowHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
        self.loadData()
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        self.refactoringWindow()
        
        NotificationCenter.default.addObserver(self, selector: #selector(doMeetingNot(not:)), name: MTDoMeetingNotification, object: nil)
    }
    
    func refactoringWindow() {
        self.view.window?.removeBgCover()
        self.view.window?.title = ""
        
        self.view.window?.hasShadow = true
        self.view.window?.toolbar = NSToolbar.init(identifier: "main_contentWindow")
        self.view.window?.titlebarAppearsTransparent = true
        self.view.window?.titleVisibility = .hidden
        self.view.window?.toolbar?.showsBaselineSeparator = false
        
        self.view.window?.styleMask = [.fullSizeContentView,.titled,.closable,.miniaturizable]
        self.view.window?.backingType = .buffered
        self.view.window?.collectionBehavior = NSWindow.CollectionBehavior.fullScreenPrimary
        self.view.window?.standardWindowButton(NSWindow.ButtonType.zoomButton)?.isHidden = true
        
        let closeBtn = self.view.window?.standardWindowButton(NSWindow.ButtonType.closeButton)
        closeBtn?.action = #selector(MainViewController.windowClose)
        closeBtn?.target = self
    }
    
    @objc func windowClose() {
        NSApp.terminate(nil)
    }
    
    
    @objc func nactiveSegmentAction(sender:NSSegmentedControl) {
        
    }
    
    func erroropen() throws {
        //let exce = NSException.init(name: NSExceptionName.init("yyyyyy"), reason: "异常处理", userInfo: nil)
        let error = NSError.init(domain: "NSException", code: 400, userInfo: nil)
        throw error
    }
    
    func setupUI()  {
        
        self.view.addSubview(leftView)
        leftView.snp.makeConstraints { (make) in
            make.width.equalTo(kLeftWidth)
            make.left.top.bottom.equalToSuperview()
        }
        
        self.view.addSubview(rightView)
        rightView.snp.makeConstraints { (make) in
            make.width.equalTo(kRightWidth)
            make.right.top.bottom.equalToSuperview()
        }
        
        
        self.leftView.addSubview(logoImgV)
        logoImgV.snp.makeConstraints { (make) in
            make.width.equalTo(600.0/3.2)
            make.height.equalTo(194.0/3.2)
            make.centerX.equalToSuperview()
            make.top.equalTo(32)
        }
        
        self.leftView.addSubview(logoLabImgV)
        logoLabImgV.snp.makeConstraints { (make) in
            make.width.equalTo(kLogo_LabWidth)
            make.height.equalTo(kLogo_LabHeight)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-30)
        }
        
        self.leftView.addSubview(meetView)
        meetView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(28)
            make.width.equalTo(140)
            make.centerY.equalToSuperview().offset(-6)
        }
        
        meetView.addSubview(meetingNum)
        meetingNum.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-1)
            make.height.equalTo(20)
        }
        
        self.leftView.addSubview(updateButtom)
        updateButtom.snp.makeConstraints { (make) in
            make.right.equalTo(-10)
            make.top.equalTo(8)
            make.height.equalTo(24)
            make.width.equalTo(80)
        }
        
        //////////////////
        self.rightView.addSubview(rightContent)
        let rightWidth = CGFloat(self.group.count)*(kMeetingX+kMeetingX_space)-kMeetingX_space
        rightContent.snp.makeConstraints { (make) in
            make.width.equalTo(rightWidth)
            make.height.equalTo(kMeetingX+45)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(10)
        }
        self.buttomAndLabel = self.initRigthtButtoms(inView: self.rightContent, group: self.group)
        
        self.view.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.width.equalTo((kIconDefault+15)*CGFloat(self.images.count))
            make.height.equalTo(kIconDefault)
            make.right.equalTo(-5)
            make.top.equalToSuperview().offset(10)
        }
        self.topButtoms = self.initTop(inView: self.topView, images: self.images)


        self.view.addSubview(protocolLab)
        protocolLab.snp.makeConstraints { (make) in
            make.height.equalTo(18)
            make.bottom.equalTo(-30)
            make.centerX.equalTo(self.rightView).offset(10)
        }

        self.view.addSubview(protocolButtom)
        protocolButtom.snp.makeConstraints { (make) in
            make.width.height.equalTo(14)
            make.bottom.equalTo(protocolLab).offset(-3)
            make.right.equalTo(protocolLab.snp.left).offset(-1)
        }
        
    }
    
    lazy var appDelegate: AppDelegate = {
        return (NSApplication.shared.delegate as! AppDelegate)
    }()
   
    lazy var topView: NSView = {
        let view = NSView()
        return view
    }()
    
    func initTop(inView:NSView,images:[String]) -> [ZHButton] {
        let spacing = CGFloat(15)
        var buttoms: [ZHButton] = []
        for (inx,val) in images.enumerated() {
            let btn = ZHButton.init()
            btn.normalImage = NSImage.init(named: NSImage.Name.init(val)) ?? NSImage.init()
            btn.selectedImage = NSImage.init(named: NSImage.Name.init(val)) ?? NSImage.init()
            btn.hoverImage = NSImage.init(named: NSImage.Name.init(val+"_selected")) ?? NSImage.init()
            btn.highlightImage = NSImage.init(named: NSImage.Name.init(val+"_selected")) ?? NSImage.init()
            btn.backgroundHighlightColor = color_main140
            btn.backgroundHoverColor = color_main140
            btn.backgroundNormalColor = NSColor.clear
            btn.backgroundSelectedColor = NSColor.clear
            btn.action = #selector(topButtomsAction(senber:))
            btn.target = self
            btn.tag = 1000+inx
            inView.addSubview(btn)
            buttoms.append(btn)
            btn.snp.makeConstraints { (make) in
                make.width.height.equalTo(kIconDefault)
                make.right.equalTo(-8-CGFloat(inx)*(kIconDefault+spacing))
                make.centerY.equalToSuperview()
            }
        }
        return buttoms
    }
    
    lazy var updateButtom: KIcon = {
        let view = KIcon.init(data: KIconGroup.init(title: "试用版", image: "icon_home_vip"))
        view.imagePosition = .left
        view.font = NSFont.systemFont(ofSize: 11)
        view.textColor = color_rgba(r: 255, g: 242, b: 190)
        view.backgroundColor = color_rgba(r: 0, g: 84, b: 240)
        view.backgroundHoverColor = color_rgba(r: 0, g: 84, b: 240, a: 0.8)
        view.layer?.cornerRadius = 6
        view.layer?.masksToBounds = true
        view.tap = { current in
            self.updateButtomAction(sender: current as? KIcon)
        }
        return view
    }()
   
    
    lazy var leftView: NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_main140.cgColor
        return view
    }()
    
    lazy var rightView: NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(255).cgColor
        return view
    }()
    
    lazy var rightContent: NSView = {
        let view = NSView()
        return view
    }()
    
    lazy var logoImgV: NSImageView = {
        let imageV = NSImageView.init()
        imageV.image = NSImage.init(named: NSImage.Name.init("mt_logo_guide_One".localized()))
        return imageV
    }()
    
    lazy var logoLabImgV: NSImageView = {
        let imageV = NSImageView.init()
        imageV.image = NSImage.init(named: NSImage.Name.init("ic_logo_lab".localized()))
        return imageV
    }()
    
    
    lazy var meetView: NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(255).cgColor
        view.layer?.cornerRadius = 15
        view.layer?.masksToBounds = true
        return view
    }()
    
    lazy var meetingNum: NSLabel = {
        let font = NSFont.init(name: "Hiragino Sans CNS", size: 18) ?? NSFont.systemFont(ofSize: 18)
        let tef = NSLabel.label(title: "00000000", textColor: color_gray(40), font: font )
        tef.alignment = .center
        return tef
    }()
   
    lazy var meetingView: NSView = {
        let view = NSView()
        return view
    }()
    
    
    func initRigthtButtoms(inView:NSView,group:[KIconGroup]) -> ([ZHButton],[NSLabel]) {
        
        var buttomAndLabel:([ZHButton],[NSLabel]) = ([],[])
        for (index,value) in group.enumerated() {
            let btn = ZHButton.init()
            btn.backgroundNormalColor = NSColor.clear
            btn.backgroundHoverColor = NSColor.clear
            btn.backgroundHighlightColor = NSColor.clear
            btn.backgroundSelectedColor = NSColor.clear
            btn.normalImage = NSImage.image(name:value.image+"_nomal") ?? NSImage.init()
            btn.selectedImage = NSImage.image(name:value.image+"_nomal") ?? NSImage.init()
            btn.hoverImage = NSImage.image(name:value.image+"_select") ?? NSImage.init()
            btn.highlightImage = NSImage.image(name:value.image+"_select") ?? NSImage.init()
            btn.hasBorder = true
            btn.zh_cornerRadius = kMeetingX/2
            btn.borderNormalColor = color_main140
            btn.borderHighlightColor = color_gray(120)
            btn.borderHoverColor = color_gray(120)
            btn.borderSelectedColor = color_main140
            btn.zh_borderWidth = 2
            btn.tag = 100+index
            btn.target = self
            btn.action = #selector(rightBottomsAction(sender:))
            inView.addSubview(btn)
            buttomAndLabel.0.append(btn)
            
            let lab = NSLabel.label(title: value.title ?? "", textColor: color_gray(0), font: NSFont.systemFont(ofSize: 16))
            lab.alignment = .center
            lab.sizeToFit()
            inView.addSubview(lab)
            buttomAndLabel.1.append(lab)
            
            btn.snp.makeConstraints { (make) in
                make.width.height.equalTo(kMeetingX)
                make.top.equalToSuperview()
                if index == 0 {
                    make.left.equalTo(0)
                }else {
                    make.left.equalTo(buttomAndLabel.0[index-1].snp.right).offset(kMeetingX_space)
                }
            }
            
            lab.snp.makeConstraints { (make) in
                make.width.equalTo(btn)
                make.height.equalTo(30)
                make.top.equalTo(btn.snp.bottom).offset(10)
                make.centerX.equalTo(btn)
            }
        }
        
        return buttomAndLabel
    }
    
    lazy var protocolLab: NSTextField = {
        let lab = NSTextField.init(frame: NSRect.zero)
        let informstring = NSMutableAttributedString()
        let normlstring = NSMutableAttributedString.init(string: "同意")
        let hyperString = NSAttributedString.init(string: "用户服务及隐私保护协议".localized(), attributes: [
            NSAttributedString.Key.link:"http://www.1meeting.cn/articledetail?aid=1202",
            //NSAttributedString.Key.underlineColor:color_main140,
            //NSAttributedString.Key.underlineStyle:NSUnderlineStyle.single,
            NSAttributedString.Key.strokeWidth:0,
            NSAttributedString.Key.strokeColor:color_main140,
        ])
        informstring.append(normlstring)
        informstring.append(hyperString)
        informstring.addAttributes([NSAttributedString.Key.font:NSFont.systemFont(ofSize: 12)], range: NSRange.init(0..<informstring.length))
        lab.attributedStringValue = informstring
        
        lab.backgroundColor = NSColor.clear
        lab.alignment = .center
        lab.isEditable = false
        lab.isBordered = false
        lab.isSelectable = true
        lab.allowsEditingTextAttributes = true
        lab.sizeToFit()
        return lab
    }()
    
    
    
    lazy var protocolButtom: MSImageView = {
        let isprotocol = self.isprotocol ? "icon_switch_on":"icon_switch_off"
        let btn = MSImageView.init(image: NSImage.image(name:isprotocol)!)
        btn.wantsLayer = true
        btn.layer?.borderColor = color_gray(0).cgColor
        btn.layer?.borderWidth = 1
        btn.layer?.cornerRadius = 0
        btn.tap = { view in
            if let img = view as? MSImageView {
                self.protocolButtomAction(sender: img)
            }
        }
        return btn
    }()
    
    @objc func protocolButtomAction(sender:MSImageView) {
        self.isprotocol = !self.isprotocol
        let isprotocol = self.isprotocol ? "icon_switch_on":"icon_switch_off"
        sender.image = NSImage.image(name:isprotocol)
    }
    
    @objc func rightBottomsAction(sender:ZHButton) {
        if Td.sh().params.userId == nil {
            show_msg("请先获取会议号")
            return
        }
        switch sender.tag {
        case 100:
            self.hostBtnAction()
        case 101:
            self.joinBtnAction()
        case 102:
            self.sharedBtnAcion()
        case 103:
            self.invateButtomAction()
        default:
            break
        }
    }
    
   
    @objc func hostBtnAction() {
        if self.isprotocol == false {
            show_msg("请同意相关服务和协议")
            return
        }
        RtcEngine.responseHostData { (result) in
            let mode = MeetingMode.deserialize(from: result)
            guard let ownid = mode?.ownid?.clear_ownid() else {
                return
            }
            OneEngine.shared.gohostmeeting(ownid: ownid, enterSuccess: {
                TrtcEngine.close(classs: [MainViewController.classForCoder()])
            }, enterFail: nil)
        }
    }
    
  
    
    @objc func joinBtnAction() {
        if self.isprotocol == false {
            show_msg("请同意相关服务和协议")
            return
        }
        
        var option = OptionData.init()
        option.roomid = ""
        option.name = UserInfoManager.shared.name ?? Td.sh().lc.nickName
        NotificationCenter.default.post(name: MTDoMeetingNotification, object: option)
    }
    
    @objc func invateButtomAction()  {
        if let ownid =  UserInfoManager.shared.ownid {
            NetEngine.accessToken(ownid: ownid) { (ciphertext) in
                let dict = [
                    "lang":"en",
                    "type":"mac",
                    "ownid":ownid,
                    "token":ciphertext
                ]
                let string = mt_url_invite + dict.urlParams()
                if let url = URL.init(string: string) {
                    NSWorkspace.shared.open(url)
                }
            }
        }
        
    }
    
    @objc func sharedBtnAcion() {
        TrtcEngine.showPreferences(onWindow:self.view.window)
    }
    
    func loadData() {
        self.localData()
        self.appDelegate.urlDelegate = self
        self.updateButtom.upText = Td.sh().cloud.isVip ? "正式版":"试用版"
    }
    
    @objc func topButtomsAction(senber:ZHButton)  {
        switch senber.tag {
        case 1000:
            self.moreAction(sender: senber)
        case 1001:
            self.introduction(sender: senber)
        case 1002:
            self.reLoadHost(success: nil)
        default:
            break
        }
    }
    func introduction(sender:NSView) {
        if let url = URL.init(string: "https://www.1meeting.cn/articledetail?aid=1263") {
           NSWorkspace.shared.open(url)
        }
    }
    
    
    func moreAction(sender:NSView)  {
        let menu = NSMenu.init()
        let p = NSPoint(x: 0, y: sender.frame.height+8)
        menu.items = self.initMenuItem()
        menu.needsUpdate()
        menu.popUp(positioning: nil, at: p, in: sender)
    }
    
    func initMenuItem() -> [NSMenuItem] {
        let titles = ["关于我们","---","版本信息"];
        var items:[NSMenuItem] = []
        for (index,value) in titles.enumerated() {
            let item = NSMenuItem.init(title: value, action: #selector(itemAction(sender:)), keyEquivalent: "")
            item.tag = index
            items.append(item)
        }
        return items
    }
    
    @objc func itemAction(sender:NSMenuItem) {
        switch sender.tag {
        case 0:
            if let url = URL.init(string: "http://www.1meeting.cn/navtech") {
               NSWorkspace.shared.open(url)
            }
        case 2:
            let window = NSWindow.init(contentViewController: VersionController.init())
            window.lorderFront(nil,makeKey: false)
        default:
            break
        }
    }
    
    @objc func updateButtomAction(sender:KIcon?) {
        let controller = VIPCenterViewController.init(days: Td.sh().cloud.days)
        let popover = NSPopover.init()
        popover.appearance = NSAppearance(named: .aqua)
        popover.behavior = .transient
        popover.animates = true
        popover.contentViewController = controller
        popover.show(relativeTo: NSRect.zero, of: sender!, preferredEdge: NSRectEdge.minY)
        
        /*
        if let url = URL.init(string: "http://www.1meeting.cn/navtech") {
           NSWorkspace.shared.open(url)
        }
        */
    }
    
}

//MARK:- 网络请求
extension MainViewController {

    //获取数据，并且缓存处理
    func localData() {
        guard let roomid = Td.sh().params.roomId else {
            self.reLoadHost(success: nil)
            return
        }
        self.meetingNum.stringValue = roomid
    }
    
    //获取host数据
    func reLoadHost(success:(([String:Any]?)->())? = nil) {
        RtcEngine.responseHostData { (result) in
            let mode = MeetingMode.deserialize(from: result)
            self.meetingNum.stringValue = mode!.ownid!.clear_ownid()
            self.updateButtom.upText = (mode?.vip == "1") ? "正式版":"试用版"
            if success != nil {
                success!(mode?.toJSON())
            }
        }
    }
}


extension MainViewController:WebSchemaDelegate {
    
    func onHandleUrl(params:[String:Any]?, type: OneRole) {
        let model = WebParamsMode.deserialize(from: params!)
        switch type {
        case .host:
            if model?.roomId != nil && (model?.ownId) != nil && (model?.name) != nil && (model?.hostId) != nil && model?.zak != nil && model?.token != nil {
                
            }
        case .join:
            if model?.roomId != nil && (model?.ownId) != nil && (model?.hostId) != nil && model?.zak != nil && model?.token != nil{
               
            }
        }
    }
}


extension MainViewController {
    @objc func doMeetingNot(not:Notification) {
        guard let option = not.object as? OptionData else {
            return
        }
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) {
            let controller = JoinViewController.init(option: option)
            controller.delegate = self
            //如果存在先删除
            self.joinViewController_closeWindow()
            let window = NSWindow.init(contentViewController: controller)
            window.animationBehavior = .alertPanel
            self.view.window?.addChildWindow(window, ordered: NSWindow.OrderingMode.above)
            window.setCenter(supWindow: self.view.window!, toRect: NSMakeRect(0, 0, kJoinWinWidth, kJoinWinHeight), animate: false)
            self.view.window?.addBgCover()
        }
    }
}


extension MainViewController:JoinVcDelegate {
    func joinViewController_closeWindow() {
        if let childWindows = self.view.window?.childWindows {
            self.view.window?.removeBgCover()
            if childWindows.count > 0{
                childWindows[0].close()
                self.view.window!.removeChildWindow(childWindows[0])
            }
            
        }
    }
}










